package com.miet.mp45.filippov.cryptoapplet.actionpanels;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFileChooser;

import org.apache.log4j.Logger;

import com.miet.mp45.filippov.crypto.util.CryptoUtil;
import com.miet.mp45.filippov.cryptoapplet.actionpanels.events.ProcessingFinishedEventListener;
import com.miet.mp45.filippov.cryptoapplet.actionpanels.events.ProcessingStartedEventListener;
import com.miet.mp45.filippov.utils.IOUtilities;

public class GenerateCertificatePanel extends ActionPanel
{

    private static final long serialVersionUID = -4408529853853873912L;

    private Logger logger = Logger.getLogger(this.getClass());
    private javax.swing.JTextField cTextField;
    private javax.swing.JTextField cnTextField;
    private javax.swing.JButton csrPathBrowseButton;
    private javax.swing.JTextField csrPathTextField;
    private javax.swing.JTextField oTextField;
    private javax.swing.JTextField ouTextField;
    private javax.swing.JButton privateKeyPathBrowseButton;
    private javax.swing.JTextField privateKeyPathTextField;
    private javax.swing.JButton signButton;
    
    
    public GenerateCertificatePanel(ProcessingStartedEventListener pseListener,
                                    ProcessingFinishedEventListener pfeListener)
    {
        addPSEListener(pseListener);
        addPFEListener(pfeListener);
        initComponents();
    }
 
    private void initComponents()
    {

        javax.swing.JLabel cnLabel = new javax.swing.JLabel();
        javax.swing.JLabel ouLabel = new javax.swing.JLabel();
        privateKeyPathBrowseButton = new javax.swing.JButton();
        privateKeyPathTextField = new javax.swing.JTextField();
        javax.swing.JLabel privateKeyPathLabel = new javax.swing.JLabel();
        cnTextField = new javax.swing.JTextField();
        ouTextField = new javax.swing.JTextField();
        signButton = new javax.swing.JButton();
        oTextField = new javax.swing.JTextField();
        javax.swing.JLabel oLabel = new javax.swing.JLabel();
        cTextField = new javax.swing.JTextField();
        javax.swing.JLabel cLabel = new javax.swing.JLabel();
        javax.swing.JLabel csrPathLabel = new javax.swing.JLabel();
        csrPathTextField = new javax.swing.JTextField();
        csrPathBrowseButton = new javax.swing.JButton();

        cnLabel.setText("CN");

        ouLabel.setText("OU");

        privateKeyPathBrowseButton.setText("...");
        privateKeyPathBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                privateKeyPathBrowseButtonActionPerformed(evt);
            }
        });

        privateKeyPathLabel.setText("Keypair path:");

        signButton.setText("Sign");
        signButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signButtonActionPerformed(evt);
            }
        });

        oLabel.setText("O");

        cLabel.setText("C");

        csrPathLabel.setText("CSR path:");

        csrPathBrowseButton.setText("...");
        csrPathBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                csrPathBrowseButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(privateKeyPathLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(privateKeyPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(privateKeyPathBrowseButton))
                            .addComponent(signButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cnLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cnTextField))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(ouLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(ouTextField)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(oLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(oTextField))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(csrPathLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(csrPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(csrPathBrowseButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cnLabel)
                    .addComponent(cnTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cLabel)
                    .addComponent(cTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ouLabel)
                    .addComponent(ouTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(oLabel)
                    .addComponent(oTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(privateKeyPathLabel)
                    .addComponent(privateKeyPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(privateKeyPathBrowseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(csrPathLabel)
                    .addComponent(csrPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(csrPathBrowseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(signButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }

    private void privateKeyPathBrowseButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        FILE_CHOOSER.setFileFilter(PRIVATE_KEY_FILE_FILTER);
        if (FILE_CHOOSER.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            privateKeyPathTextField.setText(FILE_CHOOSER.getSelectedFile().getAbsolutePath());
        }
    }

    private void csrPathBrowseButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        FILE_CHOOSER.setFileFilter(CSR_FILE_FILTER);
        if (FILE_CHOOSER.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            csrPathTextField.setText(FILE_CHOOSER.getSelectedFile().getAbsolutePath());
        }
    }
    
    private void signButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        final String csrPath = csrPathTextField.getText();
        final String pkPath = privateKeyPathTextField.getText();
        
        if (csrPath.isEmpty() || pkPath.isEmpty())
        {
            return;
        }
        
        FILE_CHOOSER.setFileFilter(CERTIFICATE_FILE_FILTER);
        if (FILE_CHOOSER.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        {
            new CryptoTask()
            {
                @Override
                public void doRun()
                {
                    FileOutputStream fos = null;
                    try
                    {
                        File file = FILE_CHOOSER.getSelectedFile();
                        logger.info("Generating X.509 certificate ...");
                        byte[] certificate = CryptoUtil.generateCertificate(IOUtilities.readFile(csrPath),
                                                                              cnTextField.getText(),
                                                                              ouTextField.getText(),
                                                                              oTextField.getText(),
                                                                              cTextField.getText(),
                                                                              IOUtilities.readFile(pkPath));
                        logger.info("Writing certificate into '" + file + "'");
                        fos = new FileOutputStream(file);
                        fos.write(certificate);
                    }
                    catch (Exception ex)
                    {
                        logger.error(ex);
                    }
                    finally
                    {
                        if (fos != null)
                        {
                            try { fos.close(); } catch (IOException ex) { logger.error(ex); }
                        }
                    }
                }
            }.start();
        }
    }

}
